import dayjs from "dayjs";
import customerTransferForm from "@/components/customerTransfer/index.vue";
import customerReleaseForm from "@/components/customerRelease/index.vue";

import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { tags_list } from "@/api/tag";
import { pro_cate_list, pro_list } from "@/api/product";
import {
  customerSalesmanData_mask,
  customer_transfer,
  customer_transfer_batch,
  customerRelease,
  customerRelease_batch
} from "@/api/customer";
import { addDialog } from "@/components/ReDialog";
import { type Ref, reactive, ref, onMounted, h, toRaw, computed } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { Phone } from "@element-plus/icons-vue";

import { useUserStoreHook } from "@/store/modules/user";

export function useRole(detailRef: Ref, releaseRef: Ref) {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_mc_cj_table: false, // 成交客户列表

    is_cd_cj_transfer: false, // 转移
    is_cd_cj_release: false, // 移入公海
  })

  const labelList = ref([]);
  const sourceList = ref([
    {
      value: "exchange",
      label: "兑领"
    },
    {
      value: "third",
      label: "第三方自导入"
    }
  ]);
  const goodSearchList = ref([]);
  const form = reactive({
    keyword: "",
    tag_id: "",
    address: "",
    product_id: [],
    status: "deal",
    page: 1,
    size: 15
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 15,
    currentPage: 1,
    background: true,
    pageSizes:[15, 30, 50, 100]
  });
  const columns = reactive<TableColumnList>([
    {
      type: "selection",
      align: "left"
    },
    {
      label: "企业名称",
      prop: "company_name",
      minWidth: 200
    },
    {
      label: "客户名称",
      prop: "name",
      minWidth: 100
    },
    {
      label: "电话",
      // prop: "phone",
      slot: "Phone",
      minWidth: 100,
      // cellRenderer: ({ row, index }) => (
      //   <>
      //     <el-icon color="#60d1d1">
      //       <Phone />
      //     </el-icon>
      //   </>
      // )
    },
    {
      label: "成交产品",
      prop: "deal_name",
      formatter: ({ deal_name }) => {
        if (!deal_name && !deal_name.length) return "";
        return deal_name.map(item => item.product_name).join(",");
      }
    },
    {
      label: "跟进记录",
      prop: "follows",
      minWidth: 300
    },
    {
      label: "地区",
      prop: "address_path",
      minWidth: 180
    },
    {
      label: "客户标签",
      prop: "tag_ids",
      minWidth: 140,
      formatter: ({ tag_ids }) => {
        if (!tag_ids) return "";
        let tagIds = tag_ids.split(",").map(item => item.replaceAll("_", ""));
        return tagIds
          .map(item => labelList.value.find(tag => tag.id === item)?.name)
          .join(",");
      }
    },
    {
      label: "来源",
      prop: "source",
      minWidth: 100,
      formatter: ({ source_by }) => {
        if (!source_by) return "";
        return sourceList.value.filter(item => item.value == source_by)[0]
          .label;
      }
    },
    {
      label: "领取时间",
      prop: "updated_at",
      minWidth: 140,
      formatter: ({ updated_at }) =>
        updated_at == 0 ? "" : dayjs.unix(updated_at).format("YYYY-MM-DD")
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ]);

  const tableRef = ref();
  const multipleSelection = ref([]);
  const detailInfo = ref();

  function lookCustomer(row) {
    detailInfo.value = row;
    detailRef.value.openDrawer(row.id, true);
  }

  function handleSizeChange(val: number) {
    form.size = val;
    pagination.pageSize = val;
    onSearch(); // 刷新表格数据
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    pagination.currentPage = val;
    onSearch(); // 刷新表格数据
  }

  function handleSelectionChange(val) {
    multipleSelection.value = val;
  }

  function handleSelectionClear() {
    const { toggleRowSelection, clearSelection } = tableRef.value.getTableRef();
    clearSelection();
  }

  // 客户转移
  const customerTransferFormRef = ref()
  function transferClick() {
    addDialog({
      title: "转移给他人",
      props: {
        formInline: {
          leader: null,
          leader_name: ""
        }
      },
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(customerTransferForm, { ref: customerTransferFormRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline;
        if (curData.leader) {
          if (multipleSelection.value.length) {
            customer_transfer_batch({
              ids: multipleSelection.value.map(item => `${item.id}:${item.table_at}:${item.version}`).join(","),
              to_target_staff_id: curData.leader
            }).then(res => {
              if (res.code == 1000) {
                message(`操作成功！`, { type: "success" });
                setTimeout(() => {
                  done(); // 关闭弹框
                  multipleSelection.value = [];
                  onSearch();
                }, 1000);
              } else {
                message(res.msg, { type: "error" });
              }
            });
          } else {
            customer_transfer({
              id: detailInfo.value.id,
              table_at: detailInfo.value.table_at,
              version: detailInfo.value.version,
              to_target_staff_id: curData.leader
            }).then(res => {
              if (res.code == 1000) {
                message(`操作成功！`, { type: "success" });
                setTimeout(() => {
                  done(); // 关闭弹框
                  detailRef.value.closeDrawer();
                  onSearch();
                }, 1000);
              } else {
                message(res.msg, { type: "error" });
              }
            });
          }
        } else {
          message(`请选择人员！`, { type: "error" });
        }
      }
    });
  }

  //释放到公海
  const customerReleaseFormRef = ref();
  function releaseClick() {
    addDialog({
      title: "释放到公海",
      props: {
        formInline: {
          id: multipleSelection.value.length ? "" : detailInfo.value.id,
          table_at: multipleSelection.value.length ? "" : detailInfo.value.table_at,
          radio: 1,
          reason: "",
          content: ""
        }
      },
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(customerReleaseForm, { ref: customerReleaseFormRef, formInline: null } ),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline
        if (curData.radio === 1) {
          if (!curData.reason) return message("请选择常见原因", { type: "warning" });
        } else {
          if (!curData.content) return message("请输入自定义原因", { type: "warning" });
        }
        if (multipleSelection.value.length) {
          customerRelease_batch({
            ids: multipleSelection.value.map(item => `${item.id}:${item.table_at}:${item.version}`).join(","),
            content: curData.radio === 1 ? curData.reason : curData.content
          }).then(res => {
            if (res.code == 1000) {
              message(`操作成功！`, { type: "success" });
              setTimeout(() => {
                done(); // 关闭弹框
                multipleSelection.value = []
                onSearch();
              }, 1000);
            } else {
              message(res.msg, { type: "error" });
            }
          });
        } else {
          customerRelease({
            id: detailInfo.value.id,
            table_at: detailInfo.value.table_at,
            version: detailInfo.value.version,
            content: curData.radio === 1 ? curData.reason : curData.content
          }).then(res => {
            if (res.code == 1000) {
              message(`操作成功！`, { type: "success" });
              setTimeout(() => {
                done(); // 关闭弹框
                detailRef.value.closeDrawer();
                onSearch();
              }, 1000);
            } else {
              message(res.msg, { type: "error" });
            }
          });
        }
      }
    });
  }

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    let queryFrom: any = { ...form };

    if (queryFrom.address && queryFrom.address.length)
      queryFrom.address = queryFrom.address.join("/");

    if (queryFrom.product_id && queryFrom.product_id.length)
      queryFrom.product_id = queryFrom.product_id[1];

    const result = await customerSalesmanData_mask(toRaw(queryFrom));

    dataList.value = result.data.list;
    pagination.total = result.data.total;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    getLabelList();
    getProCateListFn();

    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/customerManagement/myclient/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/customerManagement/myclient/index");
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);

      // mc_cj
      if (homeDataObj.mc_cj && homeDataObj.mc_cj.childs) {
        let permiss = homeDataObj.mc_cj.childs.join(',')
        permissions.is_mc_cj_table = permiss.includes('mc_cj_table') ? true : false

        if (permiss.includes('mc_cj_table')) onSearch();
      }
      // mc_cj_table
      if (homeDataObj.mc_cj_table && homeDataObj.mc_cj_table.batch) {
        // batch
        if (homeDataObj.mc_cj_table.batch && homeDataObj.mc_cj_table.batch.length) {
          let permiss = homeDataObj.mc_cj_table.batch.join(',')
          permissions.is_cd_cj_transfer = permiss.includes('cd_cj_transfer') ? true : false
          permissions.is_cd_cj_release = permiss.includes('cd_cj_release') ? true : false
        }

        let tableRemove = homeDataObj.mc_cj_table.remove ? homeDataObj.mc_cj_table.remove.split(',') : []
        for (let i = 0; i < tableRemove.length; i++) {
          for (let a = 0; a < columns.length; a++) {
            if (columns[a].prop == tableRemove[i]) {
              columns.splice(a, 1)
            }
          }
        }
      }
    }
  });

  // 获取客户标签
  function getLabelList() {
    tags_list({
      page: 1,
      pagesize: 999,
      status: 1
    }).then(res => {
      labelList.value = res.data;
    });
  }

  function removeEmptyChildren(array) {
    return array.filter(item => {
      // 如果 children 存在且不为空数组，则保留该元素
      if (item.children && item.children.length > 0) {
        // 递归处理子元素
        item.children = removeEmptyChildren(item.children);
        return true;
      }
      // 如果没有 children 属性或者 children 为空数组，则保留该元素
      return !item.hasOwnProperty("children");
    });
  }

  // 获取产品分类及列表
  function getProCateListFn() {
    pro_cate_list({
      page: 1,
      pagesize: 999
    }).then(res => {
      let cateList = res.data;
      pro_list({
        page: 1,
        pagesize: 9999
      }).then(res => {
        let goodList = res.data;
        for (let i = 0; i < cateList.length; i++) {
          cateList[i].children = [];
          for (let j = 0; j < goodList.length; j++) {
            if (goodList[j].cateId == cateList[i].id) {
              cateList[i].children.push(goodList[j]);
            }
          }
        }
        goodSearchList.value = removeEmptyChildren(cateList);
      });
    });
  }

  return {
    permissions,

    labelList,
    goodSearchList,
    form,
    loading,
    columns,
    dataList,
    pagination,
    tableRef,
    multipleSelection,

    onSearch,
    resetForm,
    lookCustomer,
    handleOffline,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleSelectionClear,

    transferClick,
    releaseClick
  };
}
